let express = require("express");
let Mock = require("mockjs")
let router = express.Router();
let multiparty = require("multiparty")
let xlsx = require("node-xlsx");
let path = require("path")
let fs = require("fs")
let ExcelJS = require("exceljs");
let {
  typeModel, // 类型
  deparmentModel, // 部门
  classroomModel, // 教室
} = require("../model/classRoomModel");

// 教室信息查询，分页，搜索
router.post("/list", async (req, res) => {
  const { page = 1, limit = 5, _id } = req.body
  let data = []
  let total = 0
  let skip = (page - 1) * limit
  delete req.body.page && delete req.body.limit
  if (Object.keys(req.body).length > 0) {
    data = await classroomModel.find({ ...req.body }).populate("apply_department").populate("availabel_types").skip(skip).limit(limit)
    total = data.length
  } else if (_id) {
    data = await classroomModel.find({ _id }).populate("apply_department").populate("availabel_types").skip(skip).limit(limit)
    total = data.length
  } else {
    data = await classroomModel.find().populate("apply_department").populate("availabel_types").skip(skip).limit(limit)
    total = data.length
  }
  res.send({
    code: 200,
    message: "查询成功",
    type: "success",
    data,
    total,
    page,
    limit,
  })
})

// 教室信息添加接口
router.post("/create", (req, res) => {
  let body = req.body
  classroomModel.create(body)
  res.send({
    code: 200,
    message: "创建成功",
    type: "success",
  })
})

// 教室模块 修改
router.post("/update", async (req, res) => {
  let { _id } = req.body
  await classroomModel.updateOne({ _id }, req.body)
  res.send({
    code: 200,
    message: "修改成功",
    type: "success",
  })
})

// 教室模块  删除
router.post("/delete", async (req, res) => {
  let { _id } = req.body
  await classroomModel.deleteOne({ _id })
  res.send({
    code: 200,
    message: "删除成功",
    type: "success"
  })
})


// 教室模块   部门信息查询
router.get("/deparmentList", async (req, res) => {
  let data = await deparmentModel.find()
  res.send({
    code: 200,
    msg: "部门列表获取成功",
    type: "success",
    data
  })
})

// 教室模块   类型信息查询
router.get("/typeList", async (req, res) => {
  let data = await typeModel.find()
  res.send({
    code: 200,
    msg: "类型列表获取成功",
    type: "success",
    data
  })
})

// 教室模块   类型添加
router.post("/typeCreate", (req, res) => {
  typeModel.create(req.body)
  res.send({
    code: 200,
    msg: "添加"
  })
})

// 教室模块   部门添加
router.post("/deparmentCreate", (req, res) => {
  deparmentModel.create(req.body)
  res.send({
    code: 200,
    msg: "添加"
  })
})



// 批量导入
router.post("/importClassRoomExcel", async (req, response) => {
  let form = new multiparty.Form()
  form.uploadDir = "assets"
  form.parse(req, (err, files, filed) => {
    let excelContent = xlsx.parse(filed.file[0].path)
    console.log(excelContent)
    let map = {
      "教室名称": "class_name",
      "所属院校": "apply_department",
      "可用状态": "current_state",
      "使用类型": "availabel_types",
    }
    let typeList = excelContent[0].data[0] // 第一行的标题
    console.log(typeList)
    let data = excelContent[0].data.slice(1)  // 所对应的数据
    data.forEach(list => {
      let json = {
        class_name: "",
        apply_department: "",
        current_state: "",
        availabel_types: "",
      }
      list.forEach((item, index) => {
        let key = map[typeList[index]]
        json[key] = item
      })
      let { class_name, apply_department, current_state, availabel_types } = json
      typeModel.find({ class_name, apply_department, current_state, availabel_types }).then(res => {
        if (res) {
          let j = { ...json }
          typeModel.updateOne({ class_name: j.class_name, apply_department: j.apply_department, current_state: j.current_state, current_state: j.current_state }, j).then(res => {
            console.log("update typeList")
          })
        } else {
          typeModel.create(json).then(res => {
            console.log("create typeList")
          })
        }
      })
    })
    response.send({
      code: 200,
      message: "上传成功",
      type: "success"
    })
  })
})


// 教室数据导出 ，分页加异步，完成
router.get("/exportClassRoomExcel", async (req, res) => {
  console.log('执行')
  /**
   * class_name
   * apply_department
   * current_state
   * availabel_types
   * create_time
   * update_time
   */
  let data = await classroomModel.find().populate("apply_department").populate("availabel_types")
  const workbook = new ExcelJS.stream.xlsx.WorkbookWriter();
  const sheet = workbook.addWorksheet('My Classroom'); // 添加工作表
  const moreConfig = {
    page: 0,
    limit: data.length >= 5000 ? 5000 : data.length,
  };
  const totalPage = Math.ceil(data.length / moreConfig.limit); // 加入一百页
  sheet.addRow(['教室名称', '所属院校', '可用状态', '使用类型']).commit()
  const write = async () => {
    if (moreConfig.page >= totalPage) {
      console.log('交工作簿');
      await workbook.commit(); // 交工作簿，即写入
      return;
    }
    console.log('\n\当前处理 page ', moreConfig.page);
    for (let i = 0; i < moreConfig.limit; i++) {
      let idx = moreConfig.page * moreConfig.limit + i
      if (Number(idx) >= data.length) break
      sheet.addRow([
        data[idx].class_name,
        data[idx].apply_department.deparment_name,
        data[idx].current_state,
        data[idx].availabel_types.type_name,
      ]).commit(); // 添加行，commit（）是将添加的行提交
      idx = null
    }
    moreConfig.page += 1;
    // 使用 setTimeout 模拟查询数据库时间
    new Promise((res) => {
      setTimeout(() => {
        res(write());
      }, 0);
    });
  };
  // 告诉浏览器这是一个二进制文件
  // res.setHeader(
  //   'Content-Type',
  //   'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  // );
  // 告诉浏览器这是一个需要下载的文件
  res.setHeader(
    'Content-Disposition',
    `attachment; filename=${encodeURIComponent('教室表')}.xlsx`
  );
  workbook.stream.pipe(res);
  Promise.resolve().then(write);
})
module.exports = router;
